package com.example.auth.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * configure of redis, will set the serialization of redis
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/6
 */
@Configuration
public class RedisConfig {

    /**
     * redisTemplate do serialization
     *
     * @param factory redisConnectionFactory
     * @return redisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // get the original redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // config the connection factory
        redisTemplate.setConnectionFactory(factory);
        // do serialization
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        // solve the problem of trans
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key is string serialization
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //hash.key is string serialization
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //value is jackson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //hash.value is jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}